package com.geeksaga.common.util;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

/**
 * @author newbie
 * @since 0.1
 */
@Component("multipartResolver")
public class AjaxFileUploadMultipartResolver extends CommonsMultipartResolver {
	public AjaxFileUploadMultipartResolver() {
		super();
	}

	public AjaxFileUploadMultipartResolver(ServletContext servletContext) {
		super();
		setServletContext(servletContext);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
		String encoding = determineEncoding(request);
		FileUpload fileUpload = prepareFileUpload(encoding);

		DiskFileItemFactory factory = new DiskFileItemFactory();
		ProgressListnerImpl progressListener = new ProgressListnerImpl(request);
		
		ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
		servletFileUpload.setSizeMax(fileUpload.getSizeMax());
		servletFileUpload.setHeaderEncoding(fileUpload.getHeaderEncoding());
		servletFileUpload.setProgressListener(progressListener);
		
		try {
			List fileItems = ((ServletFileUpload) servletFileUpload).parseRequest(request);
			MultipartParsingResult parsingResult = parseFileItems(fileItems, encoding);

			return new DefaultMultipartHttpServletRequest(request, parsingResult.getMultipartFiles(), parsingResult
					.getMultipartParameters());
		} catch (FileUploadBase.SizeLimitExceededException ex) {
			throw new MaxUploadSizeExceededException(servletFileUpload.getSizeMax(), ex);
		} catch (FileUploadException ex) {
			throw new MultipartException("Could not parse multipart servlet request", ex);
		}
	}
}